package world;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;

import media.Score;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;

public class HighScoreSystem {

	BufferedReader br;
	Score[] scoreBuffer = new Score[4];
	FileHandle highScoreFile;

	public HighScoreSystem() {
		// LinkedList<Score> highscoreListNew = new LinkedList<Score>();
		highScoreFile = Gdx.files.local("data/Memory/Highscores");
		loadHighscores();
	}

	public void addHighScore(Score newScore) {

		loadHighscores();
		scoreBuffer[3] = newScore;
		System.out.println("newscore: "
				+ scoreBuffer[3].createHighScoreString());
		printScores();
		Arrays.sort(scoreBuffer);
		printScores();
		saveHighscores();

	}

	public void saveHighscores() {
		boolean append = false;
		for (int i = 0; i < 3; i++) {
			if (i > 0)
				append = true;
			highScoreFile.writeString(scoreBuffer[i].createHighScoreString()
					+ "\n", append);
			System.out.println("saving: "
					+ scoreBuffer[i].createHighScoreString());
		}
		// }
	}

	public void loadHighscores() {

		if (highScoreFile.length() <= 0) {
System.out.println("damn lenght too short");
			highScoreFile.writeString("---------- 999.9 \n", false);
			highScoreFile.writeString("---------- 999.9 \n", true);
			highScoreFile.writeString("---------- 999.9 \n", true);

		}
		try {
			br = highScoreFile.reader((int) highScoreFile.length());
			// highscoreListNew.add(createScore(h, br.readLine()));

			for (int i = 0; i < 3; i++) {
				System.out.println(i);
				scoreBuffer[i] = createScore(i, br.readLine());

				// highscoreListNew.add(createScore(h, br.readLine()));
			}
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}

	}

	public String getScoreString(int i) {
		return scoreBuffer[i].createHighScoreString();
	}

	public void printScores() {
		int penalty = scoreBuffer[3] == null ? 1 : 0;
		System.out.println("Score print:" + scoreBuffer.length);
		for (int i = 0; i < scoreBuffer.length; i++) {
			System.out.println("" + i);
			System.out.println(scoreBuffer[i].createHighScoreString());
		}

	}

	public Score createScore(int ID, String line) {
		System.out.println(line);
		String name = line.substring(0, 11);
		float time = Float.parseFloat(line.substring(11));
		Score score = new Score(name, time);
		score.setIndex(ID);
		return score;

	}

}
